"""
此模块使用 Flask 实现用户管理的增删改查接口，
用户数据存储在本地的 user.json 文件中。
"""
import json
from typing import List
from flask import Flask, jsonify, request
from pydantic import BaseModel

# 定义用户模型
class User(BaseModel):
    id: int
    name: str
    email: str

# 初始化 Flask 应用
app = Flask(__name__)

# 定义 JSON 文件路径
JSON_FILE = "user.json"

def read_users() -> List[User]:
    """
    从 user.json 文件中读取用户数据。
    如果文件不存在或为空，则返回空列表。
    """
    try:
        with open(JSON_FILE, "r", encoding="utf-8") as file:
            data = json.load(file)
            return [User(**user) for user in data]
    except (FileNotFoundError, json.JSONDecodeError):
        return []

def write_users(users: List[User]):
    """
    将用户数据写入 user.json 文件。
    """
    with open(JSON_FILE, "w", encoding="utf-8") as file:
        user_dicts = [user.dict() for user in users]
        json.dump(user_dicts, file, ensure_ascii=False, indent=4)

# 获取所有用户
@app.route("/users", methods=["GET"])
def get_users():
    """获取所有用户信息。"""
    users = read_users()
    return jsonify([user.dict() for user in users])

# 根据 ID 获取用户
@app.route("/users/<int:user_id>", methods=["GET"])
def get_user(user_id: int):
    """根据用户 ID 获取用户信息。"""
    users = read_users()
    for user in users:
        if user.id == user_id:
            return jsonify(user.dict())
    return jsonify({"detail": "User not found"}), 404

# 创建用户
@app.route("/users", methods=["POST"])
def create_user():
    """创建新用户。"""
    users = read_users()
    new_user_data = request.get_json()
    new_user = User(**new_user_data)
    # 检查用户 ID 是否重复
    for existing_user in users:
        if existing_user.id == new_user.id:
            return jsonify({"detail": "User ID already exists"}), 400
    users.append(new_user)
    write_users(users)
    return jsonify(new_user.dict()), 201

# 更新用户
@app.route("/users/<int:user_id>", methods=["PUT"])
def update_user(user_id: int):
    """根据用户 ID 更新用户信息。"""
    users = read_users()
    updated_user_data = request.get_json()
    updated_user = User(**updated_user_data)
    for index, user in enumerate(users):
        if user.id == user_id:
            users[index] = updated_user
            write_users(users)
            return jsonify(updated_user.dict())
    return jsonify({"detail": "User not found"}), 404

# 删除用户
@app.route("/users/<int:user_id>", methods=["DELETE"])
def delete_user(user_id: int):
    """根据用户 ID 删除用户信息。"""
    users = read_users()
    for index, user in enumerate(users):
        if user.id == user_id:
            del users[index]
            write_users(users)
            return jsonify({"message": "User deleted successfully"})
    return jsonify({"detail": "User not found"}), 404

if __name__ == "__main__":
    app.run(host="0.0.0.0", port=8000, debug=True)